#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
from Ui_dialog_db_check import *
import os

class dialog_db_check(QtGui.QDialog, Ui_dialog_db_check):
    
    
    def __init__(self, parent, ontology):#, messages, error, summary):
        super(dialog_db_check,self).__init__(parent)
        
        self.setupUi(self)
        self.parent=parent
        self.ontology = ontology
        
        self.textEdit_messages.setText(QtCore.QString.fromUtf8("Database has not been checked yet."))
        
        self.connect(self.buttonBox, QtCore.SIGNAL("accepted()"),self, QtCore.SLOT("accept()"))
        self.connect(self.buttonBox, QtCore.SIGNAL("rejected()"),self, QtCore.SLOT("reject()"))
        self.connect(self.buttonBox, QtCore.SIGNAL("helpRequested()"),self.showhelp)
        
        m=QtCore.QString("")
        m.append("The database has not been checked yet.\n\n")
        m.append("It contains:\n- %d AEs\n- %d type relations\n- %d relations\n- %d type attributes\n- %d attributes\n\n"
				 %(len(self.ontology.all_AEs), len(self.ontology.all_relations_type), len(self.ontology.all_relations),len(self.ontology.all_attributes_type), len(self.ontology.all_attributes)))
        m.append("The checking process may take a few moment.")
        #self.label_summary.setText(QtGui.QApplication.translate("Dialog_db_check", str(m), None, QtGui.QApplication.UnicodeUTF8))
        self.textEdit_messages.setText(QtCore.QString.fromUtf8(m))
        #self.checkdb()
        
    def checkdb(self):        
        (messages, error, summary) = self.ontology.check_db_integrity()
        error_report = QtCore.QString("") #string type is immutable, using the QString type allows to use method "append"
        for message in messages :
            error_report.append(message)
        
        self.textEdit_messages.setText(QtCore.QString.fromUtf8(error_report))
        self.label_summary.setText(QtGui.QApplication.translate("Dialog_db_check", str(summary), None, QtGui.QApplication.UnicodeUTF8))
        
        if error :
            self.label_picture.setPixmap(QtGui.QPixmap(":/icons/messagebox_warning.png"))
            #if self.libmyCF.connector.access_mode == "write":
            self.pushButton_repair.setEnabled(True)
            self.pushButton_save.setEnabled(True)

        else :
            self.label_picture.setPixmap(QtGui.QPixmap(":/icons/apply.png"))
            
    @QtCore.pyqtSignature("bool")
    def on_pushButton_check_clicked(self):
        self.label_summary.setText(QtGui.QApplication.translate("Dialog_db_check","Checking integrity of database in progress...", None, QtGui.QApplication.UnicodeUTF8))
        self.textEdit_messages.setText(QtCore.QString.fromUtf8("please wait"))
        self.checkdb()

    @QtCore.pyqtSignature("bool")
    def on_pushButton_save_clicked(self):
    	current_directory = os.getcwd()
    	name = 'db_errors.txt'
    	log = open(name,'w')
    	log.write(unicode(self.textEdit_messages.document().toPlainText()).encode('utf-8'))
    	QtGui.QMessageBox.information(self,"myCF information","Database errors log \'%s\' has been saved in the diretory \'%s\'"%(str(name),str(current_directory)))
    	self.pushButton_save.setEnabled(False)
        
    def showhelp(self):
        QtGui.QMessageBox.information(self,"Help",
                                      str("The Auto Repair process does not repair all the erros in the database. It only repairs the following errors :\n"
                                      +"- It deletes the AE which are not connected to the MyCF tree\n"
                                      +"- It deletes the relations which appear more than once in the database\n"
                                      +"- It deletes the relations which refer to unexistant AEs\n"
                                      +"- It deletes the attributes which are not connected to AEs\n\n"
                                      +"This way, it only deletes non-functional datas and has no consequences on the mCFTree"))
        
        
        
    @QtCore.pyqtSignature("bool")
    def on_pushButton_repair_clicked(self):
        reponse = QtGui.QMessageBox.question(self, QtCore.QString("confirm"), QtCore.QString("Are you sure you want to proceed to the auto-repair ? (please check the \'help\' section before)"),
                                             QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reponse == QtGui.QMessageBox.Yes :
            corrections = self.ontology.db_repair()
            self.label_summary.setText(QtGui.QApplication.translate("Dialog_db_check","Database errors have been repaired", None, QtGui.QApplication.UnicodeUTF8))
            self.textEdit_messages.setText(QtCore.QString.fromUtf8(str("%d errors have been corrected."%corrections)))
            

         
    def accept(self):
        QtGui.QDialog.accept(self)